module.exports = (function () {
    var express = require('express');
    var router = express.Router();
    var path = require('path');
    var uid = require('uid');
    var config = require('./../config.json');
    var nameSpace = config.redisNamespace;
    var authorUrl = config.authorUrl;
    var redis = require('redis');
    router.get('/', function (req, res) {
        var uid = req.cookies.uid || null;
        var redisClient = redis.createClient();
        if (uid) {
            redisClient.del(nameSpace + ':user:' + uid);
        }
        res.clearCookie('uid');
        res.sendFile(path.join(__dirname, './authenticateViews/login.html'));
    });
    router.post('/', function (req, res) {
        res.redirect('/');
    });
    router.post('/matchCode', function (req, res) {
        var sha1 = require('sha1');
        var hash = sha1(req.body.password);
        var request = require('request');
        var redirect = req.body.redirect ? '/' + decodeURI(req.body.redirect) : '/';
        request({
            url: authorUrl + "/login",
            method: 'post',
            json: {
                userName: req.body.userName,
                password: req.body.password
            }
        }, function (error, response, body) {
                if (!error && response.statusCode === 200) {
                    //通过验证
                    res.cookie('username', body.userName, {
                        expires: new Date(Date.now() + 3600 * 1000 * 24 * 3)
                    });
                    res.cookie('uid', body.uid, {
                        expires: new Date(Date.now() + 3600 * 1000 * 24 * 3)
                    });
                    console.log('已经成功登录,重定向到', redirect);
                    //post this hash to api
                    res.send(true);
                } else {
                    res.send(false);
                    console.log('fail to log in');
                }
            });
    });
    return router;
})();
